package top.todu.demo.spirngcloud.gateway.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关的访问日志过滤器
 *
 * <p>从功能上，它类似 gsdt-spring-boot-starter-web 的 ApiAccessLogFilter 过滤器
 *
 * <p>TODO GSDT：如果网关执行异常，不会记录访问日志，后续研究下
 * https://github.com/Silvmike/webflux-demo/blob/master/tests/src/test/java/ru/hardcoders/demo/webflux/web_handler/filters/logging
 *
 * @author gsdt
 */
@Slf4j
@Component
public class AccessLogFilter implements GlobalFilter, Ordered {
  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE;
  }

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    return chain
        .filter(exchange)
        .then(
            Mono.fromRunnable(
                () -> {
                  log.info(
                      "网关日志：uri:{}, targetSchema: {}",
                      exchange.getRequest().getURI(),
                      exchange.getAttributeOrDefault("targetSchema", "http"));
                }));
  }
}
